package io.gitee.yanbinchen;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * @author: alex
 * @since : 2025-02-28 17:44
 */
public class SuperCacheService {
    @Autowired
    RedisTemplate<String, byte[]> superCacheTemplate;

    public void setCache(String key, Object obj, SuperKey superKey) {
        if (superKey.isArray()) {
            byte[] bytes = ProtostuffUtils.serializeList((List) obj, superKey.clzName());
            bytes = BizUtils.zip(bytes);
            superCacheTemplate.opsForValue().set(key,bytes);
        } else {
            byte[] bytes = ProtostuffUtils.serializer(obj);
            bytes = BizUtils.zip(bytes);
            superCacheTemplate.opsForValue().set(key,bytes);
        }
    }

    public <T> T getCache(String key,Class<T> clz,SuperKey superKey){
        byte[] bytes = superCacheTemplate.opsForValue().get(key);
        if (bytes==null||bytes.length==0){
            return null;
        }
        bytes = BizUtils.unzip(bytes);
        if (superKey.isArray()){
            return (T)ProtostuffUtils.deserializeList(bytes,clz);
        }else {
            return ProtostuffUtils.deserializer(bytes,clz);
        }
    }

    public void unlink(String key){
        superCacheTemplate.unlink(key);
    }
}
